var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var common = require('../../utils/common.js');
var Base = require('../../common/CmptBase.js');
var app = getApp();

var CutList = function({
  page,
  scope,
  showType,
}) {
  Base.apply(this, arguments);

  this._timerList = {};
  this._timerId = null;
  this._showType = showType || 0;
  this.init();
}

common.extend(CutList, Base);

Object.assign(CutList.prototype, {
  init() {
    var _self = this;

    ajax.G({
      url: '/market/Activity/haggleActList',
      data: {
        show_type: this._showType
      },
      success: (res) => {
        var list = res.result || [];

        list.forEach(function(item, index) {
          var leftTime = item.left_time;

          if (leftTime && leftTime > 0) {
            _self._timerList[index] = leftTime;
          }

          item['goods_info']['image_url'] = item['goods_info']['image_url'].split('|')[0];
        });
        _self.setData({
          list,
          timerStrs: {}
        });

        if (_self._timerId) {
          clearTimeout(_self._timerId);
        }
        _self._timerDown();
      }
    });
  },

  _timerDown() {
    var _self = this;
    var timerStrs = _self.getData('timerStrs');
    var _timerList = _self._timerList;
    var isOver = false;
    var _timerListKeys = Object.keys(_timerList);

    if (_timerListKeys.length == 0) {
      return;
    }
    _timerListKeys.some(function(key) {
      var sec = _timerList[key];

      timerStrs[key] = util.getTimeBySec(sec, 'd');

      if (sec == 0) {
        isOver = true;
        return true;
      }
      _timerList[key] = --sec;
    });

    if (isOver) {
      _self.init();
      clearTimeout(self._timerId);
      return;
    }
    _self.setData({
      timerStrs,
    });
    _self._timerId = setTimeout(() => {
      _self._timerDown();
    }, 1000);
  },

});

module.exports = CutList;